package com.cm.order.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cm.common.entity.User;
import com.cm.order.entity.Address;
import com.cm.order.entity.dto.AddressKeyWordDTO;
import com.cm.order.entity.vo.AddressVO;
import com.cm.order.feign.UserFeign;
import com.cm.order.mapper.AddressMapper;
import com.cm.order.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @类 名:AddressServiceImpl </br>
 * @描 述:<br>
 * @日 期:2020/9/25 17:05 </br>
 * @作 者:小兰同学</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private UserFeign userFeign;
    @Override
    public boolean insert(Address address) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",address.getUserId());
        List<Address> brands = addressMapper.selectList(queryWrapper);
        if(brands.size() > 0){
            return false;
        }
        addressMapper.insert(address);
        return true;
    }

    @Override
    public boolean delete(Long id) {
        if(addressMapper.deleteById(id) > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean update(Address address) {
        if (addressMapper.updateById(address) > 0){
            return true;
        }
        return false;
    }

    @Override
    public IPage<AddressVO> getAddresstList(AddressKeyWordDTO addressKeyWordDTO) {
        Page<AddressVO> page = new Page<>();
        addressKeyWordDTO.setCurrentPage((addressKeyWordDTO.getCurrentPage()-1)*addressKeyWordDTO.getPageSize());
        List<AddressVO> cartList=addressMapper.getAddressList(addressKeyWordDTO);
        for (AddressVO add:cartList){
            Map<String,String> user= (Map<String,String>) userFeign.getUserById(add.getUserId()).getData();
            add.setAccount(user.get("account"));
        }
        page.setRecords(cartList);
        page.setCurrent(addressKeyWordDTO.getCurrentPage());
        page.setSize(addressKeyWordDTO.getPageSize());
        int count=addressMapper.getAddressTotal(addressKeyWordDTO);
        page.setTotal(count);
        return page;
    }

    @Override
    public Address getByUserId(Long id) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",id);
        Address address=addressMapper.selectOne(queryWrapper);
        return address;
    }
}
